import echarts from 'echarts'
// import { getWaterData } from '@/api/charts'
// import waterChartData from './mock/water-charts'
import moment from 'moment'

const waterLine = {
  _waterChart: null,
  _waterData: [],

  _lineOptions: {
    animation: false,
    legend: {
      data: []
    },
    tooltip: {
      trigger: 'axis',
      formatter: params => {
        const data = params[0].data
        // console.log(data)
        const tooltip =
          `<div class="tooltip-container"><span class="tooltip-title"><b>时间:</b> ` +
          `${moment(data.time).format('YYYY-MM-DD HH:mm')}` +
          `</span><br/><span class="tooltip-title"><b>水位:</b> ` +
          `${data.value !== null ? data.value : ' '}` +
          `(m)</span></div>`
        return tooltip
      }
      /* axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }*/
    },
    grid: {
      show: true,
      top: '43px',
      left: '35px',
      right: '18px',
      bottom: '37px',
      backgroundColor: '#f5f5f5',
      borderColor: '#cccccc'
    },
    toolbox: {
      show: false,
      feature: {
        mark: {
          show: true
        },
        dataView: {
          show: true,
          readOnly: false
        },
        restore: {
          show: true
        },
        saveAsImage: {
          show: true
        }
      }
    },
    calculable: false,
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: []
      }
    ],
    yAxis: [
      {
        name: '水位(m)',
        type: 'value',
        splitArea: {
          show: true
        }
      }
    ],
    series: [
      {
        name: '水位',
        type: 'line',
        symbol: 'emptyCircle',
        symbolSize: 3,
        // showAllSymbol: true,
        itemStyle: {
          color: 'green',
          borderColor: 'green',
          borderWidth: 1
        },
        lineStyle: {
          color: 'green',
          width: 1
        },
        data: []
      }
    ]
  },

  _setMarkPointOffset(params) {
    let minOffset = [0, 22]
    let maxOffset = [0, -22]
    let minSymbolOffset = [0, 3.5]
    let minSymbolRotate = 0
    // console.log(params.data[0])
    const data = params.data
    const waterMin = params.waterMin
    const waterMax = params.waterMax
    const firstData = data[0]
    const lastData = data[data.length - 1]
    const halfIntervalHour = Math.abs(moment(firstData.time).diff(moment(lastData.time), 'hour')) / 2
    const fistMinHour = waterMin && Math.abs(moment(firstData.time).diff(moment(waterMin.time), 'hour'))
    const lastMinHour = waterMin && Math.abs(moment(lastData.time).diff(moment(waterMin.time), 'hour'))
    const fistMaxHour = waterMax && Math.abs(moment(firstData.time).diff(moment(waterMax.time), 'hour'))
    const lastMaxHour = waterMax && Math.abs(moment(lastData.time).diff(moment(waterMax.time), 'hour'))
    if (waterMin && waterMin.time && fistMinHour <= 3 && fistMinHour < halfIntervalHour) {
      minOffset = [80, 22]
    } else if (waterMin && waterMin.time && lastMinHour <= 3 && lastMinHour < halfIntervalHour) {
      minOffset = [-80, 22]
    }

    if (waterMax && waterMax.time && fistMaxHour <= 3 && fistMaxHour < halfIntervalHour) {
      maxOffset = [80, -22]
    } else if (waterMax && waterMax.time && lastMaxHour <= 3 && lastMaxHour < halfIntervalHour) {
      maxOffset = [-80, -22]
    }

    if (waterMin && waterMin.val && waterMin.val < waterMax.val / 2) {
      minSymbolRotate = 180
      minSymbolOffset = [0, -3.5]
      minOffset[1] = -22
    }

    // console.log(0,
    //   firstData,
    //   waterMin,
    //   Math.abs(moment(firstData.time).diff(moment(waterMin.time), 'hour'))
    // )
    return {
      minOffset: minOffset,
      maxOffset: maxOffset,
      minSymbolRotate: minSymbolRotate,
      minSymbolOffset: minSymbolOffset
    }
  },

  _fetchData(stcd, tm) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // resolve(waterChartData)
      }, 300)
    })
    // return new Promise((resolve, reject) => {
    //   getWaterData(stcd, tm)
    //     .then(response => {
    //       resolve(response.data)
    //     })
    //     .catch(error => {
    //       reject(error)
    //     })
    // })
  },

  init(divId) {
    var lineOptions = this._lineOptions
    var waterChart = echarts.init(document.getElementById(divId))
    waterChart.clear()
    waterChart.setOption(lineOptions)
    this._waterChart = waterChart
  },

  showLoading() {
    var waterChart = this._waterChart
    waterChart.showLoading({
      text: '加载中...',
      color: '#3398DB'
    })
  },

  hideLoading() {
    var waterChart = this._waterChart
    waterChart.hideLoading()
  },

  update(fetchData) {
    var lineOptions = this._lineOptions
    var waterChart = this._waterChart
    this._waterData = []
    // lineOptions.series[0].data = {}
    // lineOptions.series[0].markLine = {}
    // lineOptions.series[0].markPoint = {}
    // lineOptions.xAxis.data = []

    this._waterData = fetchData

    if (!this._waterData.data.length) {
      return
    }

    lineOptions.xAxis = [
      {
        type: 'category',
        boundaryGap: false,
        data: this._waterData.data.map(d => d.time),
        axisLabel: {
          formatter: value => {
            return moment(value)
              .format('HH:mm MM-DD')
              .replace(' ', '\n')
          }
        }
      }
    ]

    lineOptions.series[0].data = this._waterData.data.map(d => {
      return { time: d.time, value: d.val }
    })

    var waterMax
    var waterMin
    var waterMaxIndex = 0
    var waterMinIndex = 0
    this._waterData.data.forEach((item, index) => {
      if (item.val !== null && !waterMax) {
        waterMax = item
        waterMaxIndex = index
      }
      if (item.val !== null && !waterMin) {
        waterMin = item
        waterMinIndex = index
      }
      if (item.val !== null && item.val > waterMax.val) {
        waterMax = item
        waterMaxIndex = index
      }
      if (item.val !== null && item.val < waterMin.val) {
        waterMin = item
        waterMinIndex = index
      }
    })

    // console.log(waterMin, waterMinIndex, waterMax, waterMaxIndex)

    const offsets = this._setMarkPointOffset({
      data: this._waterData.data,
      waterMin: waterMin,
      waterMax: waterMax
    })

    lineOptions.series[0].markLine = {
      symbol: ['none', 'none'],
      label: {
        normal: {
          show: true
        }
      },
      lineStyle: {
        normal: {
          color: 'green',
          width: 1,
          type: 'dashed'
        }
      },
      data: []
    }

    if (waterMin) {
      lineOptions.series[0].markLine.data.push({
        xAxis: this._waterData.data[waterMinIndex].time,
        label: {
          show: false
        },
        tooltip: {
          show: false
        }
      })
    }

    if (waterMax) {
      lineOptions.series[0].markLine.data.push({
        xAxis: this._waterData.data[waterMaxIndex].time,
        label: {
          show: false
        },
        tooltip: {
          show: false
        }
      })
    }

    lineOptions.series[0].markPoint = {
      itemStyle: {
        opacity: 0.6,
        color: 'green'
      },
      label: {
        color: '#ffffff'
      },
      data: []
    }

    if (waterMin) {
      lineOptions.series[0].markPoint.data.push(
        {
          symbol: 'triangle',
          symbolRotate: offsets.minSymbolRotate,
          symbolSize: [10, 5],
          symbolOffset: offsets.minSymbolOffset,
          value: '',
          coord: [waterMinIndex, (waterMin && waterMin.val) || null],
          label: {
            show: true
          },
          tooltip: {
            show: false
          }
        },
        {
          symbol: 'rect',
          symbolSize: [170, 33],
          symbolOffset: offsets.minOffset,
          coord: [waterMinIndex, (waterMin && waterMin.val) || null],
          label: {
            show: true,
            align: 'left',
            offset: [-80, 0],
            formatter: [
              `最低水位：${
                waterMin.val != null ? waterMin.val : ' '
              }m\n发生时间：${moment(waterMin.time).format('YYYY-MM-DD HH:mm')}`
            ].join('\n')
          },
          tooltip: {
            show: false
          }
        }
      )
    }

    if (waterMax) {
      lineOptions.series[0].markPoint.data.push(
        {
          symbol: 'triangle',
          symbolRotate: 180,
          symbolSize: [10, 5],
          symbolOffset: [0, -3.5],
          value: '',
          coord: [waterMaxIndex, (waterMax && waterMax.val) || null],
          label: {
            show: true,
            borderRadius: 10
          },
          tooltip: {
            show: false
          }
        },
        {
          symbol: 'rect',
          coord: [waterMaxIndex, (waterMax && waterMax.val) || null],
          symbolSize: [170, 33],
          symbolOffset: offsets.maxOffset,
          label: {
            show: true,
            align: 'left',
            offset: [-80, 0],
            formatter: [
              `最高水位：${
                waterMax.val !== null ? waterMax.val : ' '
              }m\n发生时间：${moment(waterMax.time).format('YYYY-MM-DD HH:mm')}`
            ].join('\n')
          },
          tooltip: {
            show: false
          }
        }
      )
    }

    waterChart.setOption(lineOptions)
  },

  async Render(divId, stcd, tm) {
    var lineOptions = this._lineOptions
    this._waterData = []
    // lineOptions.series[0].data = {}
    // lineOptions.series[0].markLine = {}
    // lineOptions.series[0].markPoint = {}
    // lineOptions.xAxis.data = []
    var waterChart = echarts.init(document.getElementById(divId))
    waterChart.clear()
    waterChart.setOption(lineOptions)

    waterChart.showLoading({
      text: '加载中...',
      color: '#3398DB'
    })
    this._waterData = await this._fetchData(stcd, tm)
    waterChart.hideLoading()

    if (!this._waterData.data.length) {
      return
    }

    // var data1 = this._waterData.xAxisData.map(function(x) {
    //   return x.replace(' ', '\n')
    // })

    lineOptions.xAxis = [
      {
        type: 'category',
        boundaryGap: false,
        data: this._waterData.data.map(d => d.time),
        axisLabel: {
          formatter: value => {
            return moment(value)
              .format('HH:mm MM-DD')
              .replace(' ', '\n')
          }
        }
      }
    ]

    lineOptions.series[0].data = this._waterData.data.map(d => {
      return { time: d.time, value: d.val }
    })

    var waterMax
    var waterMin
    var waterMaxIndex = 0
    var waterMinIndex = 0
    this._waterData.data.forEach((item, index) => {
      if (!waterMax) waterMax = item
      if (!waterMin) waterMin = item
      if (item.val < waterMax.val) {
        waterMax = item
        waterMaxIndex = index
      }
      if (item.val > waterMin.val) {
        waterMin = item
        waterMinIndex = index
      }
    })

    const offsets = this._setMarkPointOffset({
      data: this._waterData.data,
      waterMin: waterMin,
      waterMax: waterMax
    })

    lineOptions.series[0].markLine = {
      symbol: ['none', 'none'],
      label: {
        normal: {
          show: true
        }
      },
      lineStyle: {
        normal: {
          color: '#1db55d',
          width: 2,
          type: 'dashed'
        }
      },
      data: [
        {
          xAxis: this._waterData.data[waterMinIndex].time,
          label: {
            show: false
          },
          tooltip: {
            show: false
          }
        },
        {
          xAxis: this._waterData.data[waterMaxIndex].time,
          label: {
            show: false
          },
          tooltip: {
            show: false
          }
        }
      ]
    }

    lineOptions.series[0].markPoint = {
      itemStyle: {
        opacity: 0.8,
        color: '#1db55d'
      },
      label: {
        color: '#ffffff'
      },
      data: [
        {
          symbol: 'triangle',
          symbolRotate: offsets.minSymbolRotate,
          symbolSize: [10, 5],
          symbolOffset: offsets.minSymbolOffset,
          value: '',
          coord: [waterMinIndex, waterMin.val],
          label: {
            show: true
          },
          tooltip: {
            show: false
          }
        },
        {
          symbol: 'triangle',
          symbolRotate: 180,
          symbolSize: [10, 5],
          symbolOffset: [0, -3.5],
          value: '',
          coord: [waterMaxIndex, waterMax.val],
          label: {
            show: true,
            borderRadius: 10
          },
          tooltip: {
            show: false
          }
        },
        {
          symbol: 'rect',
          coord: [waterMaxIndex, waterMax.val],
          symbolSize: [170, 33],
          symbolOffset: offsets.maxOffset,
          label: {
            show: true,
            align: 'left',
            offset: [-80, 0],
            formatter: [
              '最高水位：' + waterMax.val
                ? waterMax.val
                : '' +
                  'm\n发生时间：' +
                  moment(waterMax.time).format('YYYY-MM-DD HH:mm')
            ].join('\n')
          },
          tooltip: {
            show: false
          }
        },
        {
          symbol: 'rect',
          symbolSize: [170, 33],
          symbolOffset: offsets.minOffset,
          coord: [waterMinIndex, waterMin.val],
          label: {
            show: true,
            align: 'left',
            offset: [-80, 0],
            formatter: [
              '最低水位：' + waterMin.val
                ? waterMin.val
                : '' +
                  'm\n发生时间：' +
                  moment(waterMin.time).format('YYYY-MM-DD HH:mm')
            ].join('\n')
          },
          tooltip: {
            show: false
          }
        }
      ]
    }

    // lineOptions.series[0].markPoint = {
    //   symbolSize: 22,
    //   // symbolRotate:180,
    //   label: { fontSize: 8 /*, offset:[0,5]*/ },
    //   data: [
    //     { name: '谷', type: 'min' },
    //     { name: '峰', type: 'max' }
    //     // {
    //     //   name: '最新',
    //     //   coord: [
    //     //     this._waterData.xAxisData[this._waterData.xAxisData.length - 1],
    //     //     this._waterData.seriesData[this._waterData.seriesData.length - 1]
    //     //   ],
    //     //   value: this._waterData.seriesData[
    //     //     this._waterData.seriesData.length - 1
    //     //   ]
    //     // }
    //   ]
    // }

    waterChart.setOption(lineOptions)
  }
}

export default waterLine
